﻿using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.Sales_Purchase;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.Sales_Purchase.BreedingSales
{
    /// <summary>
    /// 销售
    /// </summary>
    public class BreedingSalesCreateHandler : IRequestHandler<BreedingSalesCreateCommon, Result>
    {
        private readonly IBaseRepository<SalesRecord> salesRecordRep; 
        private readonly IBaseRepository<SleepInfor> sleepinforRep;
        /// <summary>
        /// 销售
        /// </summary>
        public BreedingSalesCreateHandler(IBaseRepository<SalesRecord> salesRecordRep, IBaseRepository<SleepInfor> sleepinforRep)
        {
            this.salesRecordRep = salesRecordRep;
            this.sleepinforRep = sleepinforRep;
        }

        public async Task<Result> Handle(BreedingSalesCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result { Code = (int)CodeEnum.add };
            try
            {
                // 尝试添加数据
                var n = await salesRecordRep.AddRange(request.salesRecord);
                // 检查添加结果
                if (n > 0) // 假设 AddAsync 返回的 n 是影响的行数或插入的 ID
                {
                    // 更新 SleepInfor 表的栋舍栏位
                    request.salesRecord.ForEach(x =>
                    {
                        var list = sleepinforRep.GetAll().FirstOrDefault(c => c.SleepInforId == x.EarTag);
                        list.RecordcottageId = x.Barn;
                        list.FieIdId = x.Stall; 
                        list.StayStatus = 0;
                        sleepinforRep.Update(list);
                    });

                    result.Code = (int)CodeEnum.success;
                    result.Messege = "添加成功";
                }
                else
                {
                    result.Messege = "添加失败";
                }
            }
            catch (Exception)
            {
                result.Messege = "添加异常";
                throw;
            }
            return result;
        }
    }
}
